package com.smart.manager.task;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.smart.common.annotation.TaskBean;
import com.smart.common.annotation.TaskMethod;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.domain.TaskResult;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.product.entities.assembler.ReqRfid;
import com.smart.manager.product.entities.enums.PigStatus;
import com.smart.manager.product.entities.enums.RfidStatus;
import com.smart.manager.product.entities.enums.RfidUseStatus;
import com.smart.manager.product.entities.models.BasicRfid;
import com.smart.manager.product.entities.models.query.QBasicRfid;
import com.smart.manager.system.repository.ConfigRepository;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 获取耳标任务
 *
 * @author leo
 * &#064;date  2024/03/06
 */
@Log4j2
@Component
@TaskBean
@RequiredArgsConstructor
public class RfidDataTaskV1 {

    private final ConfigRepository configRepository;

    /**
     * 每小时更新耳标数据
     *
     * @return {@link TaskResult}
     */

    @TaskMethod(title = "更新耳标数据")
    public synchronized TaskResult earTagDataV1() {
        try {


            //默认数据
            int start = 200;
            int end = 400;
            //更新所有已入栏的猪耳标
            Random rand = new Random();
            LocalDateTime dateTime = LocalDateTime.now();
            String format = dateTime.format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
            //所有猪
            List<MemberMaterialPig> pigList = new QMemberMaterialPig().status.eq(PigStatus.NORMAL).findList();
            Map<String, MemberMaterialPig> pigMap = pigList.stream()
                    .collect(Collectors.toMap(x->x.getRfid().getBeaconMac(), Function.identity(), (existing, replacement) -> existing));
            JSONObject object = configRepository.readCache("Temperature");
            //所有耳标地址
            Set<String> macSet = pigList.stream().map(x -> x.getRfid().getBeaconMac()).collect(Collectors.toSet());
            List<BasicRfid> rfidList = new QBasicRfid().beaconMac.in(macSet).findList();
            rfidList.forEach(rxf -> {
                //设置耳标状态
                rxf.setStatus(RfidStatus.ONLINE).setUseStatus(RfidUseStatus.USING).setRfidUpdateTime(format);

                //设置猪仔体温
                MemberMaterialPig pig = pigMap.get(rxf.getBeaconMac());
                String degree = null;
                switch (pig.getPigLevel().getStage()){
                    case SMALL:
                         degree = object.getString("small");
                        break;
                    case DURING:
                         degree = object.getString("middle");
                        break;
                    case LARGE:
                         degree = object.getString("large");
                        break;
                    default:
                        degree = "38.0-39.5";
                }
                String[] temperatureParts = degree.split("-");
                double firstNumber = Double.parseDouble(temperatureParts[0]);
                double secondNumber = Double.parseDouble(temperatureParts[1]);
                String temperature = NumberUtil.round(Math.random() * (secondNumber - firstNumber) + firstNumber, 2).toString();
                rxf.setTemperature(temperature);

                //设置猪仔步数
                int hour = dateTime.plusHours(-1).getHour();
                String rfidData = configRepository.readCache("RfidData").getString(String.valueOf(hour));
                String[] parts = rfidData.split("-");
                int starts = Integer.parseInt(parts[0]);
                int ends = Integer.parseInt(parts[1]);
                if (ObjUtil.isNull(rxf.getShake())){
                    rxf.setShake(String.valueOf(0));
                }
                if (ends > starts) {
                    int nextInt = ThreadLocalRandom.current().nextInt(starts, ends);
                    BigDecimal decimal = NumberUtil.round(NumberUtil.add(nextInt, Double.parseDouble(rxf.getShake())), 0);
                    rxf.setShake(decimal.toString());
                } else {
                    int nextInt = ThreadLocalRandom.current().nextInt(start, end);
                    BigDecimal decimal = NumberUtil.round(NumberUtil.add(nextInt, Double.parseDouble(rxf.getShake())), 0);
                    rxf.setShake(decimal.toString());
                }

            });
            DB.updateAll(rfidList);
        } catch (Exception e) {
            e.printStackTrace();
            return new TaskResult(false, "更新失败");
        }
        return new TaskResult(true, "更新成功");
    }

}
